using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlServerCe;
using System.IO;

namespace SQLServerCEMergeReplicationExample
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button btnCreateSubscription;
        private System.Windows.Forms.Button btnSynchronize;
        private System.Windows.Forms.Button btnAddClient;
        private System.Windows.Forms.Button btnReinitializeSubscription;
        private System.Windows.Forms.Button btnDropSubscription;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnCreateSubscription = new System.Windows.Forms.Button();
            this.btnSynchronize = new System.Windows.Forms.Button();
            this.btnAddClient = new System.Windows.Forms.Button();
            this.btnReinitializeSubscription = new System.Windows.Forms.Button();
            this.btnDropSubscription = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnCreateSubscription
            // 
            this.btnCreateSubscription.Location = new System.Drawing.Point(8, 8);
            this.btnCreateSubscription.Name = "btnCreateSubscription";
            this.btnCreateSubscription.Size = new System.Drawing.Size(144, 20);
            this.btnCreateSubscription.TabIndex = 4;
            this.btnCreateSubscription.Text = "Create Subscription";
            this.btnCreateSubscription.Click += new System.EventHandler(this.btnCreateSubscription_Click);
            // 
            // btnSynchronize
            // 
            this.btnSynchronize.Location = new System.Drawing.Point(8, 40);
            this.btnSynchronize.Name = "btnSynchronize";
            this.btnSynchronize.Size = new System.Drawing.Size(144, 20);
            this.btnSynchronize.TabIndex = 3;
            this.btnSynchronize.Text = "Synchronize";
            this.btnSynchronize.Click += new System.EventHandler(this.btnSynchronize_Click);
            // 
            // btnAddClient
            // 
            this.btnAddClient.Location = new System.Drawing.Point(8, 72);
            this.btnAddClient.Name = "btnAddClient";
            this.btnAddClient.Size = new System.Drawing.Size(144, 20);
            this.btnAddClient.TabIndex = 2;
            this.btnAddClient.Text = "Add Client";
            this.btnAddClient.Click += new System.EventHandler(this.btnAddClient_Click);
            // 
            // btnReinitializeSubscription
            // 
            this.btnReinitializeSubscription.Location = new System.Drawing.Point(8, 104);
            this.btnReinitializeSubscription.Name = "btnReinitializeSubscription";
            this.btnReinitializeSubscription.Size = new System.Drawing.Size(144, 20);
            this.btnReinitializeSubscription.TabIndex = 1;
            this.btnReinitializeSubscription.Text = "Reinitialize Subscription";
            this.btnReinitializeSubscription.Click += new System.EventHandler(this.btnReinitializeSubscription_Click);
            // 
            // btnDropSubscription
            // 
            this.btnDropSubscription.Location = new System.Drawing.Point(8, 136);
            this.btnDropSubscription.Name = "btnDropSubscription";
            this.btnDropSubscription.Size = new System.Drawing.Size(144, 20);
            this.btnDropSubscription.TabIndex = 0;
            this.btnDropSubscription.Text = "Drop Subscription";
            this.btnDropSubscription.Click += new System.EventHandler(this.btnDropSubscription_Click);
            // 
            // Form1
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.ClientSize = new System.Drawing.Size(240, 294);
            this.Controls.Add(this.btnDropSubscription);
            this.Controls.Add(this.btnReinitializeSubscription);
            this.Controls.Add(this.btnAddClient);
            this.Controls.Add(this.btnSynchronize);
            this.Controls.Add(this.btnCreateSubscription);
            this.MinimizeBox = false;
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        static void Main()
        {
            Application.Run(new Form1());
        }

        private void btnCreateSubscription_Click(object sender, System.EventArgs e)
        {
            SqlCeReplication rep = null;

            try
            {
                btnCreateSubscription.Enabled = false;
                rep = new SqlCeReplication();

                // This is the connection string to your local SQL Server CE database file
                rep.SubscriberConnectionString = "Data Source=\\My Documents\\" +
                    "gXX.sdf;" +
                    "SSCE:Database Password=gXX";

                // If database doesn't exist then...
                if (!File.Exists("\\My Documents\\gXX.sdf"))
                {
                    // Add a subscription and create the local database
                    rep.AddSubscription(AddOption.CreateDatabase);
                }
            }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlError in sqlex.Errors)
                {
                    MessageBox.Show(sqlError.Message, "Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                rep.Dispose();
                btnCreateSubscription.Enabled = true;
            }
        }

        private void btnSynchronize_Click(object sender, System.EventArgs e)
        {
            SqlCeReplication rep = null;

            try
            {
                btnSynchronize.Enabled = false;
                rep = new SqlCeReplication();

                // This is the URL that points to sscesa20.dll running on IIS
                rep.InternetUrl = "http://cmovel.rnl.ist.utl.pt/gXX/sqlcesa30.dll";

                // This is your Basic Authentication username
                rep.InternetLogin = @"cmovel\gXX";

                // This is your Basic Authentication password
                rep.InternetPassword = "password";

                // This is the name of the server running SQL Server
                rep.Publisher = @"cmovel\CMOVEL";

                // This is the name of the actual database that you're publishing
                rep.PublisherDatabase = "gXX-db1";

                // This is the type of authentication you're using
                rep.PublisherSecurityMode = SecurityType.NTAuthentication;

                // This is the name that you give to your publication
                // during the wizard setup
                rep.Publication = "gXX";

                // This anonymous subscriber name can be anything you want it to be
                rep.Subscriber = "Subscriber";

                // This is the connection string to your local SQL Server CE database file
                rep.SubscriberConnectionString = "Data Source=\\My Documents\\" +
                    "gXX.sdf;" +
                    "SSCE:Database Password=gXX";

                // If database already exists then...
                if (File.Exists("\\My Documents\\gXX.sdf"))
                {
                    // Synchronize with SQL Server
                    rep.Synchronize();
                }
                else
                {
                    MessageBox.Show("You must first create a database", "Error");
                }
            }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlError in sqlex.Errors)
                {
                    MessageBox.Show(sqlError.Message, "Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                rep.Dispose();
                btnSynchronize.Enabled = true;
            }
        }

        private void btnAddClient_Click(object sender, System.EventArgs e)
        {
			// This example assumes that the database contains a table called 'teste' with
			// an 'id' field and a 'name' field

            SqlCeConnection cn = null;

            try
            {
                btnAddClient.Enabled = false;
                cn = new SqlCeConnection("Data Source=\\My Documents\\" +
                    "gXX.sdf;" +
                    "SSCE:Database Password=gXX");
                cn.Open();

                SqlCeCommand cmd = cn.CreateCommand();

                // Insert Memo Data
                cmd.CommandText = "INSERT INTO teste (" +
                    "id, " +
                    "name) " +
                    "VALUES " +
                    //"(4, \"teste\")";
                    "(?, ?)";
                cmd.Parameters.Add("@id", 4);
                cmd.Parameters.Add("@name", "teste");
                cmd.Prepare();
                cmd.ExecuteNonQuery();
            }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlError in sqlex.Errors)
                {
                    MessageBox.Show(sqlError.Message, "Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
                btnAddClient.Enabled = true;
            }
        }

        private void btnReinitializeSubscription_Click(object sender, System.EventArgs e)
        {
            SqlCeReplication rep = null;

            try
            {
                btnReinitializeSubscription.Enabled = false;
                rep = new SqlCeReplication();

                // This is the URL that points to sscesa20.dll running on IIS
                rep.InternetUrl = "http://cmovel.rnl.ist.utl.pt/gXX/sqlcesa30.dll";

                // This is your Basic Authentication username
                rep.InternetLogin = @"cmovel\gXX";

                // This is your Basic Authentication password
                rep.InternetPassword = "password";

                // This is the name of the server running SQL Server
                rep.Publisher = @"cmovel\CMOVEL";

                // This is the name of the actual database that you're publishing
                rep.PublisherDatabase = "gXX-db1";

                // This is the type of authentication you're using
                rep.PublisherSecurityMode = SecurityType.NTAuthentication;

                // This is the name that you give to your publication
                // during the wizard setup
                rep.Publication = "gXX";

                // This anonymous subscriber name can be anything you want it to be
                rep.Subscriber = "Subscriber";

                // This is the connection string to your local SQL Server CE database file
                rep.SubscriberConnectionString = "Data Source=\\My Documents\\" +
                    "gXX.sdf;" +
                    "SSCE:Database Password=gXX";

                // If database already exists then...
                if (File.Exists("\\My Documents\\gXX.sdf"))
                {
                    // This uploads your changes and then marks the
                    // subscription for reinitialization
                    rep.ReinitializeSubscription(true);

                    // Synchronize with SQL Server
                    rep.Synchronize();
                }
                else
                {
                    MessageBox.Show("You must first create a database", "Error");
                }
            }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlError in sqlex.Errors)
                {
                    MessageBox.Show(sqlError.Message, "Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                rep.Dispose();
                btnReinitializeSubscription.Enabled = true;
            }
        }

        private void btnDropSubscription_Click(object sender, System.EventArgs e)
        {
            SqlCeReplication rep = null;

            try
            {
                btnDropSubscription.Enabled = false;
                rep = new SqlCeReplication();

                // This is the connection string to your local SQL Server CE database file
                rep.SubscriberConnectionString = "Data Source=\\My Documents\\" +
                    "gXX.sdf;" +
                    "SSCE:Database Password=gXX";

                // If database already exists then...
                if (File.Exists("\\My Documents\\gXX.sdf"))
                {
                    // This drops the subscription and deletes the database
                    rep.DropSubscription(DropOption.LeaveDatabase);
                }
                else
                {
                    MessageBox.Show("You must first create a database", "Error");
                }
            }
            catch (SqlCeException sqlex)
            {
                foreach (SqlCeError sqlError in sqlex.Errors)
                {
                    MessageBox.Show(sqlError.Message, "Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                rep.Dispose();
                btnDropSubscription.Enabled = true;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

    }
}
